﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.Web;
using System.IO;

namespace NetLib.web
{
    public class HttpPost
    {
        protected static String GetCharacterSet(byte[] data)
        {
            string s = Encoding.Default.GetString(data);
            return GetCharacterSet(s);
        }
        protected static String GetCharacterSet(string s)
        {
            s = s.ToUpper();
            int start = s.LastIndexOf("CHARSET");
            if (start == -1)
                return "";

            start = s.IndexOf("=", start);
            if (start == -1)
                return "";

            start++;
            s = s.Substring(start).Trim();
            int end = s.Length;

            int i = s.IndexOf(";");
            if (i != -1)
                end = i;
            i = s.IndexOf("\"");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("'");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("/");
            if (i != -1 && i < end)
                end = i;

            return s.Substring(0, end).Trim();
        }

        protected static byte[] ReadStream(Stream s)
        {
            try
            {
                byte[] buffer = new byte[8096];
                using (MemoryStream ms = new MemoryStream())
                {
                    while (true)
                    {
                        int read = s.Read(buffer, 0, buffer.Length);
                        if (read <= 0)
                        {
                            return ms.ToArray();
                        }
                        ms.Write(buffer, 0, read);
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static String RequestCSV(String url, Hashtable parameter, out bool success)
        {
            ServicePointManager.Expect100Continue=false;
            String ps = ParameterUtils.EncodeURLParameter(parameter);
            byte[] postdata = Encoding.UTF8.GetBytes(ps);

            String result = "";
            success = false;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "POST";
            req.AllowAutoRedirect = true;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postdata.Length;


            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(postdata, 0, postdata.Length);
            }
            //--------------------------------------------------------
            //Read

            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.NotModified)
                    {
                        byte[] buffer = null;
                        using (Stream s = resp.GetResponseStream())
                        {
                            buffer = ReadStream(s);
                        }
                        string pageEncoding = "";
                        Encoding e = Encoding.UTF8;

                        if (String.IsNullOrWhiteSpace(resp.ContentEncoding) == false)
                            pageEncoding = resp.ContentEncoding;
                        else if (String.IsNullOrWhiteSpace(resp.CharacterSet) == false)
                            pageEncoding = resp.CharacterSet;
                        else if (resp.ContentType != "")
                        {
                            if (resp.ContentType.Contains("csv"))
                            {
                                pageEncoding = "big5";
                            }
                            else
                            {
                                pageEncoding = GetCharacterSet(resp.ContentType);
                            }
                        }
                        if (String.IsNullOrWhiteSpace(pageEncoding))
                            pageEncoding = GetCharacterSet(buffer);


                        if (pageEncoding != "")
                        {
                            try
                            {
                                e = Encoding.GetEncoding(pageEncoding);
                                result = e.GetString(buffer);
                                success = true;
                            }
                            catch (Exception ex)
                            {
                                result = "ERROR:" + ex.Message;
                                //  message=("Invalid encoding: " + pageEncoding);

                            }
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                result = "ERROR:" + ex.Message;
            }

            return result;
        }

        public static String RequestHtml(string url, Hashtable parameter, Encoding enc, Hashtable headers = null)
        {


            return null;
        }
        public static string Request(string url, Hashtable parameter, Encoding enc, Hashtable headers = null)
        {
            ServicePointManager.Expect100Continue = false;
            if (headers == null)
                headers = new Hashtable();
            String result = "";
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = enc;
                if (null != headers)
                    foreach (String k in headers.Keys)
                    {
                        wc.Headers.Add(k, (String)headers[k]);
                    }
                
                
                String ps=ParameterUtils.EncodeURLParameter(parameter);
                /*
                 *
                 StringBuilder sb = new StringBuilder();
                foreach (String k in parameter.Keys)
                {
                    sb.Append(k);
                    sb.Append("=");
                    String v = (String)parameter[k];
                    v = HttpUtility.UrlEncode(v);
                    sb.Append(v);
                    sb.Append("&");
                }
                String ps = sb.ToString();
                 **/

                var URI = new Uri(url);
                if (headers.Contains("Content-Type") == false)
                    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                try
                {

                    byte[] postdata = Encoding.UTF8.GetBytes(ps);
                    byte[] responsedata = wc.UploadData(url, postdata);




                    String contentBig5 = System.Text.Encoding.GetEncoding("big5").GetString(responsedata);
                    String contentUtf8 = System.Text.Encoding.UTF8.GetString(responsedata);

                    if (Encoding.UTF8.Equals(enc))
                        result = contentUtf8;
                    else
                        result = contentBig5;

                }
                catch (Exception e)
                {
                    result = "Error:" + e.Message;
                }
            }
            return result;
        }
    }

}
